/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2005-2025 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.axelor.demo;

import com.axelor.common.ObjectUtils;
import com.axelor.common.StringUtils;
import com.axelor.project.db.ProjectTask;
import com.axelor.project.db.repo.ProjectTaskRepository;
import com.google.inject.persist.Transactional;
import java.util.Arrays;
import java.util.Map;
import javax.inject.Inject;

public class ProjectImport {

  private final ProjectTaskRepository taskRepository;

  @Inject
  public ProjectImport(ProjectTaskRepository taskRepository) {
    this.taskRepository = taskRepository;
  }

  @Transactional
  public Object importTask(Object bean, Map context) {
    var task = (ProjectTask) bean;
    var subTaskNamesString = (String) context.get("subTasks[].name");

    if (StringUtils.notBlank(subTaskNamesString)) {
      var subTaskNames = Arrays.asList(subTaskNamesString.split("\\s*\\|\\s*"));
      if (ObjectUtils.notEmpty(subTaskNames)) {
        taskRepository
            .all()
            .filter("self.name IN :names")
            .bind("names", subTaskNames)
            .fetch()
            .forEach(task::addSubTask);
      }
    }

    return task;
  }
}
